package com.qingzhuge.manager.security.handler;

import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.manager.dto.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author zeroxiao
 * @date 2019/9/12 14:01
 * @description
 */
@Slf4j
@Component
public class LoginAuthenticationEventListener implements ApplicationListener<AbstractAuthenticationEvent> {
    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(AbstractAuthenticationEvent event) {
        Authentication authentication = (Authentication) event.getSource();
        String simpleName = event.getClass().getSimpleName();
        log.debug("登录:[{}]",simpleName);
        if (event instanceof AuthenticationSuccessEvent){
            log.debug("登录Success:[{}]", simpleName);
            SecurityUser user = (SecurityUser) authentication.getPrincipal();
            AbstractController.setUsername(user.getUsername());
            AbstractController.setUid(user.getId());
        }else if (event instanceof AuthenticationFailureBadCredentialsEvent){
            log.debug("登录FailureBadCredentials:[{}]",simpleName);
        }else if(event instanceof AbstractAuthenticationFailureEvent){
            log.debug("登录Failure:[{}]",simpleName);
        }
        log.debug("登录:[{}]",authentication);
    }
}
